<template>
	<!-- 加载中 -->
	<uni-load-more :status="loadingStatus" v-if="isLoading" />

	<view v-else class="task-stats-container">
		<!-- 顶部维度选择器 -->
		<view class="dimension-selector">
			<view class="selector-header">
				<text class="selector-title">📊 数据统计</text>
				<text
					class="selector-subtitle">{{ timeDimensions.find(d => d.value === activeDimension)?.label }}数据</text>
			</view>
			<view class="dimension-tabs">
				<view v-for="dimension in timeDimensions" :key="dimension.value"
					:class="['dimension-tab', { active: activeDimension === dimension.value }]"
					@tap="switchToDimension(dimension.value)">
					<text class="tab-label">{{ dimension.label }}</text>
				</view>
			</view>
		</view>

		<!-- 主内容区域 - 水平滑动的swiper -->
		<swiper class="main-swiper" horizontal="true" circular="false" :current="getDimensionIndex(activeDimension)"
			@change="onSwiperChange" :disable-scroll="false">
			<!-- 根据时间维度渲染swiper-item -->
			<swiper-item v-for="dimension in timeDimensions" :key="dimension.value" class="swiper-slide">
				<view class="slide-content" ref="slideContentRef">
					<view v-if="getStatsByType(parseInt(dimension.value))" class="stats-card">
						<!-- 统计网格 -->
						<view class="stats-grid">
							<!-- 已完成任务 -->
							<view class="stats-grid-item stats-item-completed">
								<view class="stats-icon">✓</view>
								<text
									class="stats-value">{{ getStatsByType(parseInt(dimension.value))?.completedTasks || 0 }}</text>
								<text class="stats-label">已完成</text>
							</view>

							<!-- 待完成任务 -->
							<view class="stats-grid-item stats-item-pending">
								<view class="stats-icon">⏰</view>
								<text
									class="stats-value">{{ getStatsByType(parseInt(dimension.value))?.pendingTasks || 0 }}</text>
								<text class="stats-label">待完成</text>
							</view>

							<!-- 完成率 -->
							<view class="stats-grid-item stats-item-rate">
								<view class="stats-icon">📈</view>
								<text
									class="stats-value">{{ calculateCompletionRate(parseInt(dimension.value)) }}%</text>
								<text class="stats-label">完成率</text>
							</view>

							<!-- 得分 -->
							<view class="stats-grid-item stats-item-score">
								<view class="stats-icon">⭐</view>
								<text class="stats-value">{{ getScoreByType(parseInt(dimension.value)) || 0 }}</text>
								<text class="stats-label">总得分</text>
							</view>
						</view>
					</view>
				</view>
			</swiper-item>
		</swiper>
	</view>
</template>

<script setup lang="ts">
	import { ref, onMounted, computed } from 'vue';
	import { StatsItem } from '@/types';
	import { listStatsAPI } from '@/services/task';
	import { getThemeStyles } from '@/stores/theme';

	/**
	 * 统计数据数组
	 */
	const statisticsData = ref<StatsItem[]>([]);

	/**
	 * 数据加载状态
	 */
	const isLoading = ref(true);


	/**
	 * 加载状态文本
	 */
	const loadingStatus = ref('more');

	/**
	 * 下拉刷新状态
	 */
	const isRefresher = ref(false);

	/**
	 * 时间维度选项
	 */
	const timeDimensions = ref([
		{ label: '周', value: '1' },
		{ label: '月', value: '2' },
		{ label: '年', value: '3' },
		{ label: '全部', value: '4' }
	]);

	/**
	 * 当前激活的时间维度
	 */
	const activeDimension = ref('1');

	/**
	 * 幻灯片内容引用
	 */
	const slideContentRef = ref<HTMLElement[]>();

	/**
	 * 获取当前主题样式
	 */
	const themeStyles = computed(() => getThemeStyles());

	/**
	 * 处理下拉刷新
	 */
	const onRefresh = async () => {
		try {
			await loadTaskStatsData();
		} finally {
			// 无论成功失败都要停止刷新状态
			isRefresher.value = false;
		}
	};


	/**
	 * 根据类型获取统计数据
	 * @param type 统计类型
	 * @returns 对应的统计数据项
	 */
	const getStatsByType = (type : number) : StatsItem | undefined => {
		return statisticsData.value.find(stat => stat?.type === type);
	};

	/**
	 * 获取时间维度对应的索引
	 */
	const getDimensionIndex = (dimension : string) => {
		return timeDimensions.value.findIndex(item => item.value === dimension);
	};

	/**
	 * 处理swiper切换
	 */
	const onSwiperChange = (e : any) => {
		const index = e.detail.current;
		activeDimension.value = timeDimensions.value[index]?.value || activeDimension.value;
	};

	/**
	 * 切换到指定维度
	 */
	const switchToDimension = (dimension : string) => {
		activeDimension.value = dimension;
	};

	/**
	 * 计算任务完成率
	 * @param type 统计类型
	 * @returns 完成率百分比
	 */
	const calculateCompletionRate = (type : number) : number => {
		const stat = getStatsByType(type);
		if (!stat) return 0;

		// 处理可能的undefined值
		const completedTasks = stat.completedTasks || 0;
		const pendingTasks = stat.pendingTasks || 0;
		const totalTasks = completedTasks + pendingTasks;

		// 避免除以0
		if (totalTasks === 0) return 0;

		// 计算完成率并四舍五入到整数
		return Math.round((completedTasks / totalTasks) * 100);
	};

	/**
	 * 调用任务统计API获取数据
	 * @returns 任务统计数据数组
	 */
	const getTaskStatsAPI = async () : Promise<StatsItem[]> => {
		try {
			const result = await listStatsAPI();
			return result.data;
		} catch (error) {
			console.error('获取任务统计数据失败:', error);
			return []; // 出错时返回空数组，避免页面白屏
		}
	};

	/**
	 * 加载任务统计数据
	 */
	const loadTaskStatsData = async () : Promise<void> => {
		try {
			isLoading.value = true;
			loadingStatus.value = 'more';
			const result = await getTaskStatsAPI();
			// 确保result是有效的数组
			statisticsData.value = Array.isArray(result) ? result : [];
		} catch (error) {
			console.error('加载任务统计数据失败:', error);
			statisticsData.value = [];
		} finally {
			setTimeout(() => {
				isLoading.value = false;
				loadingStatus.value = 'more';
			}, 500);
		}
	};

	/**
	 * 根据类型获取得分
	 * @param type 统计类型
	 * @returns 对应的得分
	 */
	const getScoreByType = (type : number) : number => {
		const stat = getStatsByType(type);
		return stat.totalScore;
		;
	};
	// 页面加载时获取数据
	onMounted(() => {
		loadTaskStatsData();
	});
</script>

<style lang="scss">
	// 容器样式
	.task-stats-container {
		width: 100%;
		height: 50vh;
		max-height: 50vh;
		display: flex;
		flex-direction: column;
		background: v-bind('themeStyles.bgPrimary');
		padding: 20rpx 0;
		box-sizing: border-box;
		overflow: hidden;
	}

	// 维度选择器
	.dimension-selector {
		background: v-bind('themeStyles.bgCard');
		padding: 20rpx 16rpx;
		margin: 0 20rpx 16rpx 20rpx;
		border-radius: 16rpx;
		border: 1rpx solid v-bind('themeStyles.borderLight');
		box-shadow: v-bind('themeStyles.cardBoxShadow');
		flex-shrink: 0;
		max-height: 120rpx;
	}

	.selector-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 12rpx;
		padding-bottom: 8rpx;
		border-bottom: 1rpx solid v-bind('themeStyles.borderLight');
	}

	.selector-title {
		font-size: 24rpx;
		font-weight: 600;
		color: v-bind('themeStyles.textPrimary');
	}

	.selector-subtitle {
		font-size: 20rpx;
		color: v-bind('themeStyles.textTertiary');
		padding: 2rpx 8rpx;
		background: v-bind('themeStyles.accentBg');
		border-radius: 8rpx;
		border: 1rpx solid v-bind('themeStyles.accentBorder');
	}

	.dimension-tabs {
		display: flex;
		gap: 8rpx;
	}

	.dimension-tab {
		flex: 1;
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 10rpx 8rpx;
		background: v-bind('themeStyles.bgSecondary');
		border: 2rpx solid v-bind('themeStyles.borderLight');
		border-radius: 8rpx;
		transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);

		&:active {
			transform: scale(0.96);
		}
	}

	.tab-label {
		font-size: 22rpx;
		font-weight: 500;
		color: v-bind('themeStyles.textSecondary');
	}

	.dimension-tab.active {
		background: v-bind('themeStyles.primaryGradient');
		border-color: v-bind('themeStyles.primaryColor');
		box-shadow: v-bind('themeStyles.activeShadow');
		transform: translateY(-2rpx);

		.tab-label {
			color: white;
			font-weight: 600;
		}
	}

	// 主内容swiper
	.main-swiper {
		flex: 1;
		width: 100%;
		height: calc(50vh - 160rpx);
		margin: 0 20rpx;
		overflow: hidden;
	}

	.swiper-slide {
		width: 100%;
		height: 100%;
		overflow: hidden;
	}

	// 内容区域
	.slide-content {
		padding: 0;
		height: 100%;
		display: flex;
		flex-direction: column;
		animation: slideIn 0.4s ease-out;
		overflow: hidden;
	}

	@keyframes slideIn {
		from {
			opacity: 0;
			transform: translateX(20rpx);
		}

		to {
			opacity: 1;
			transform: translateX(0);
		}
	}

	// 统计卡片
	.stats-card {
		background: v-bind('themeStyles.bgCard');
		border-radius: 20rpx;
		padding: 24rpx 20rpx;
		box-shadow: v-bind('themeStyles.cardBoxShadow');
		border: 1rpx solid v-bind('themeStyles.borderLight');
		transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
		flex: 1;
		display: flex;
		flex-direction: column;
		height: 100%;
		max-height: 100%;
		overflow: hidden;
	}

	// 统计网格
	.stats-grid {
		display: grid;
		grid-template-columns: repeat(2, 1fr);
		gap: 16rpx;
		flex: 1;
		align-content: center;
		grid-template-rows: repeat(2, 1fr);
	}

	// 统计项基础样式
	.stats-grid-item {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 20rpx 16rpx;
		background: v-bind('themeStyles.bgSecondary');
		border-radius: 16rpx;
		border: 2rpx solid v-bind('themeStyles.borderLight');
		transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
		position: relative;
		overflow: hidden;
		min-height: 100rpx;

		&:hover {
			transform: translateY(-2rpx);
			box-shadow: v-bind('themeStyles.hoverBoxShadow');
		}

		&:active {
			transform: scale(0.96);
		}
	}

	// 统计图标
	.stats-icon {
		font-size: 40rpx;
		margin-bottom: 8rpx;
		animation: iconBounce 0.5s ease-out;
		filter: drop-shadow(0 2rpx 4rpx rgba(0, 0, 0, 0.1));
	}

	@keyframes iconBounce {

		0%,
		100% {
			transform: scale(1);
		}

		50% {
			transform: scale(1.1);
		}
	}

	// 统计值
	.stats-value {
		font-size: 48rpx;
		font-weight: 700;
		margin-bottom: 6rpx;
		color: v-bind('themeStyles.textPrimary');
		line-height: 1.1;
	}

	// 统计标签
	.stats-label {
		font-size: 22rpx;
		color: v-bind('themeStyles.textSecondary');
		font-weight: 500;
		text-align: center;
	}

	// 已完成样式
	.stats-item-completed {
		background: linear-gradient(135deg, rgba(16, 185, 129, 0.12) 0%, rgba(16, 185, 129, 0.04) 100%);
		border-color: rgba(16, 185, 129, 0.3);

		.stats-value {
			color: v-bind('themeStyles.successColor');
		}
	}

	// 待完成样式
	.stats-item-pending {
		background: linear-gradient(135deg, rgba(245, 158, 11, 0.12) 0%, rgba(245, 158, 11, 0.04) 100%);
		border-color: rgba(245, 158, 11, 0.3);

		.stats-value {
			color: v-bind('themeStyles.warningColor');
		}
	}

	// 完成率样式
	.stats-item-rate {
		background: linear-gradient(135deg, rgba(59, 130, 246, 0.12) 0%, rgba(59, 130, 246, 0.04) 100%);
		border-color: rgba(59, 130, 246, 0.3);

		.stats-value {
			color: v-bind('themeStyles.infoColor');
		}
	}

	// 得分样式
	.stats-item-score {
		background: linear-gradient(135deg, rgba(168, 85, 247, 0.12) 0%, rgba(168, 85, 247, 0.04) 100%);
		border-color: rgba(168, 85, 247, 0.3);

		.stats-value {
			color: #a855f7;
		}
	}
</style>